package com.example.showlocation;

import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.os.Looper;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;

import com.example.showlocation.adapter.ItemAdapter;
import com.tencent.map.geolocation.TencentLocation;
import com.tencent.map.geolocation.TencentLocationListener;
import com.tencent.map.geolocation.TencentLocationManager;
import com.tencent.map.geolocation.TencentLocationRequest;

import java.io.IOException;

public class AddLocationActivity extends AppCompatActivity {
    String name=null;
    EditText editText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_location_activity);
    }
    @SuppressLint("UseCompatLoadingForDrawables")
    protected void onStart() {
        name=getIntent().getStringExtra("name");
        editText= (EditText)findViewById(R.id.editText);
        TextWatcher textWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                // ignore
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                // ignore
            }

            @Override
            public void afterTextChanged(Editable editable) {
                editText.setAlpha(1);
            }
            /*@Override
            public void afterTextChanged(Editable s) {
                String  editTextText= editText.getText().toString();
                SuggestionSearch mSuggestionSearch = SuggestionSearch.newInstance();

                OnGetSuggestionResultListener listener = new OnGetSuggestionResultListener()
                {
                    @Override
                    public void onGetSuggestionResult(SuggestionResult suggestionResult) {
                        stringArray= new String[suggestionResult.getAllSuggestions().size()];
                        //处理sug检索结果
                        for (int i = 0; i <suggestionResult.getAllSuggestions().size() ; i++) {
                            stringArray[i] =suggestionResult.getAllSuggestions().get(i).address;


                        }
                        RecyclerView recyclerView = findViewById(R.id.recyclerView_1);

                        ItemAdapter itemAdapter = new ItemAdapter(getApplicationContext(),stringArray);
                        recyclerView.setAdapter(itemAdapter);

                    }
                };
                mSuggestionSearch.setOnGetSuggestionResultListener(listener);
                mSuggestionSearch.requestSuggestion(new SuggestionSearchOption()
                        .city("北京")
                        .keyword(editTextText));

            }*/

        };
        editText.addTextChangedListener(textWatcher);
        CompoundButton.OnCheckedChangeListener onCheckedChangeListener=new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                Intent intent=new Intent(getApplicationContext(), SendLocationActivity.class);
                intent.putExtra("isGetLocation",false);
                startActivity(intent);
            }
        };
        try {
            AddLocation_Tencent( onCheckedChangeListener);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        super.onStart();
        Log.d(getLocalClassName()+":", "onStart()");
    }
    @Override
    protected void onResume() {
        super.onResume();
        //Explore();
        Log.d(getLocalClassName()+":", "onResume()");
    }
    /*private void AddLocation_BD() throws Exception {

        class MyLocationListener extends BDAbstractLocationListener {
            @Override
            public void onReceiveLocation(BDLocation bdLocation) {

                String addr = bdLocation.getAddrStr();    //获取详细地址信息
                String country = bdLocation.getCountry();    //获取国家
                String province = bdLocation.getProvince();    //获取省份
                String city = bdLocation.getCity();    //获取城市
                String district = bdLocation.getDistrict();    //获取区县
                String street = bdLocation.getStreet();    //获取街道信息
                String town = bdLocation.getTown();    //获取乡镇信息

                String[][] myDataset =new String[bdLocation.getPoiList().size()][2];

                for (int i = 0; i <bdLocation.getPoiList().size() ; i++) {
                    myDataset[i][0]=bdLocation.getPoiList().get(i).getName();
                    myDataset[i][1]=bdLocation.getPoiList().get(i).getAddr();

                }
                RecyclerView recyclerView = findViewById(R.id.recyclerView);

                ItemAdapter itemAdapter = new ItemAdapter(getApplicationContext(),myDataset);
                recyclerView.setAdapter(itemAdapter);
            }
        }

        MyLocationListener myListener = new MyLocationListener();
        LocationClient.setAgreePrivacy(true);
        LocationClient mLocationClient =new LocationClient(getApplicationContext()) ;
        mLocationClient.registerLocationListener(myListener);

        LocationClientOption option = new LocationClientOption();
        option.setIsNeedAddress(true);
        option.setNeedNewVersionRgc(true);

        mLocationClient.setLocOption(option);

        mLocationClient.start();
        }*/
    private void AddLocation_Tencent(CompoundButton.OnCheckedChangeListener onCheckedChangeListener) throws Exception {

        /*TelephonyManager telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);*/
        TencentLocationManager mLocationManager = TencentLocationManager.getInstance(this);
        TencentLocationManager.setUserAgreePrivacy(true);
        mLocationManager.setDeviceID(getApplicationContext(), DeviceIdUtil.getDeviceId(this));
        Log.d("getDeviceId()"+":", DeviceIdUtil.getDeviceId(this));
        class MyLocationListener implements TencentLocationListener {
            @Override
            public void onLocationChanged(TencentLocation location, int error, String reason) {
                String[][] myDataset =new String[location.getPoiList().size()+2][3];

                for (int i = 0; i <location.getPoiList().size()+2 ; i++) {
                    if (i == 0){
                        myDataset[i][0]="null";
                    }else{if (i == 1){
                        myDataset[i][0]=location.getCity() ;
                        myDataset[i][1]=location.getNation()+location.getProvince()+location.getCity();
                    }else{
                        myDataset[i][0]=location.getPoiList().get(i-2).getName();
                        myDataset[i][1]=location.getPoiList().get(i-2).getAddress();
                        myDataset[i][2]= String.valueOf(location.getPoiList().get(i-2).getDistance());

                    }}
                }
                RecyclerView recyclerView = findViewById(R.id.recyclerView);
                ItemAdapter itemAdapter = new ItemAdapter(myDataset,onCheckedChangeListener);
                recyclerView.setAdapter(itemAdapter);
                Log.d("AddLocationActivity:", "onLocationChanged");
            }

            @Override
            public void onStatusUpdate(String name, int status, String desc) {
                /**
                 * name - 设备名, GPS, WIFI, CELL 中的某个
                 * status - 状态码, STATUS_ENABLED, STATUS_DISABLED, STATUS_UNKNOWN, STATUS_GPS_AVAILABLE, STATUS_GPS_UNAVAILABLE, STATUS_DENIED中的某个 在使用status之前,请先按照name进行区分
                 * desc - 状态描述
                 */
            }

            }
        MyLocationListener mLocationListener=new MyLocationListener() ;
        TencentLocationRequest request = TencentLocationRequest.create();
        request.setRequestLevel( TencentLocationRequest.REQUEST_LEVEL_POI);
        request.setGpsFirst(true);
        mLocationManager.requestSingleFreshLocation(request , mLocationListener, Looper.getMainLooper());
        }
    @SuppressLint("IntentReset")
    public void sendMessage_1(View view) throws IOException, PendingIntent.CanceledException {
        Intent intent=new Intent(this, SendLocationActivity.class);
        Log.d(getLocalClassName()+":", String.valueOf(R.id.constraintLayout1));
        Log.d(getLocalClassName()+":", String.valueOf(R.id.textView));
        if (view.getId()==R.id.constraintLayout1){
            name= (String) ((TextView)view.findViewById(R.id.textView11)).getText();
            intent.putExtra("isGetLocation",true);
        }else {
            intent.putExtra("isGetLocation",false);
        }
        /*switch (view.getId()){
            case R.id.constraintLayout1:
                name= (String) ((TextView)view.findViewById(R.id.textView11)).getText();
                intent.putExtra("isGetLocation",true);
                break;
            case R.id.textView:
                intent.putExtra("isGetLocation",false);
        }*/
        intent.putExtra("name",name);
        startActivity(intent);
    }
}
    /*private void Explore() throws IOException {
        URL url=new URL("https://apis.map.qq.com/ws/place/v1/search?boundary=nearby(40.040589,116.273543,1000)&keyword=公园&page_size=10&page_index=1&key=LEOBZ-REXL3-ZFC3B-ONA76-64FTJ-RUFES");
      //URL url=new URL("https://apis.map.qq.com/ws/place/v1/explore?boundary=nearby(40.040394,116.273523,1000,1)&policy=1&page_size=10&page_index=1&key=LEOBZ-REXL3-ZFC3B-ONA76-64FTJ-RUFES");
      //URL url=new URL("https://apis.map.qq.com/ws/location/v1/ip?key=LEOBZ-REXL3-ZFC3B-ONA76-64FTJ-RUFES");
      //URL url=new URL("https://cn.bing.com/");
        URLConnection urlConnection=url.openConnection();
        *//*URLConnection urlConnection=new URLConnection(url) {
            @Override
            public void connect() throws IOException {

                Log.d("AddLocationActivity:",
                "connect()");
        }};*//*
        urlConnection.setUseCaches(true);
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        urlConnection.setAllowUserInteraction(true);
        urlConnection.setRequestProperty("method","get");

        *//*for (int i = 0; i < urlConnection.getRequestProperties().size(); i++) {
        }*//*
        //Log.d("inputStream", urlConnection.getRequestProperty("method"));
        byte[] bytes=new byte[1];
        //byte[] bytes;

        new Thread(new Runnable() {
            public void run() {
                Looper.prepare();
                try {
                    urlConnection.connect();
                    //urlConnection.getContent();



                    Log.d("inputStream",urlConnection.getContentType());
                    Log.d("inputStream", String.valueOf(urlConnection.getContentLength()));
                    *//*Log.d("inputStream",urlConnection.getHeaderField("current_pv"));
                    Log.d("inputStream",urlConnection.getHeaderField("limit_pv"));*//*
                    Log.d("inputStream",urlConnection.getContent().toString());
                    int n;
                    InputStream inputStream=

                        urlConnection.getInputStream();

                    InputStreamReader inputStreamReader =
                            new InputStreamReader(inputStream, StandardCharsets.UTF_8);
                    StringBuilder stringBuilder = new StringBuilder();
                    try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
                        String line = reader.readLine();
                        while (line != null) {
                            stringBuilder.append(line).append('\n');
                            line = reader.readLine();
                        }
                    } catch (IOException e) {
                        // Error occurred when opening raw file for reading.
                    } finally {
                        String contents = stringBuilder.toString();
                        Log.d("inputStream", contents);
                    }
                    *//*while ( ( n=inputStream.read(bytes))!=-1 ) {


                        fileOutputStream.write(bytes,0,n);
                        fileOutputStream.flush();

                    }

                    inputStream.close();
                    inputStream.close();*//*

                    //Log.d("inputStream","completed" );



                    //Log.d("AddLocationActivity:", String.valueOf(urlConnection.getContent()));
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                Looper.loop();
            }
        }).start();
       // urlConnection.connect();
        //urlConnection.setAllowUserInteraction(true);

        *//*if (urlConnection.getAllowUserInteraction()){
            Log.d("AddLocation_BDActivity:", String.valueOf(urlConnection.getContent()));
        }else{
            urlConnection.setAllowUserInteraction(true);
            Log.d("AddLocation_BDActivity:", String.valueOf(urlConnection.getContent()));
        }*//*


        //URL url=new URL("https://apis.map.qq.com/ws/place/v1/search?boundary=nearby(40.040589,116.273543,1000)&keyword=公园&page_size=10&page_index=1&key=LEOBZ-REXL3-ZFC3B-ONA76-64FTJ-RUFES");
        *//*HttpsURLConnection httpsURLConnection=new HttpsURLConnection(url) {
            @Override
            public String getCipherSuite() {
                return null;
            }

            @Override
            public Certificate[] getLocalCertificates() {
                return new Certificate[0];
            }

            @Override
            public Certificate[] getServerCertificates() throws SSLPeerUnverifiedException {
                return new Certificate[0];
            }

            @Override
            public void disconnect() {

            }

            @Override
            public boolean usingProxy() {
                return false;
            }

            @Override
            public void connect() throws IOException {

            }
        };*//*
        //httpsURLConnection.connect();



}
ArrayList<View> radioButtonArrayList=new ArrayList<>(1);
//recyclerView.getChildAt(0).addFocusables(radioButtonArrayList, View.FOCUS_BACKWARD);
RadioButton radioButton=new RadioButton(getApplicationContext());
radioButtonArrayList.add(radioButton);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        Log.d("AddLocationActivity_sendMessage_1:", String.valueOf(view.getFocusable()));
        }
//view.setBackgroundColor(Color.parseColor("#040404"));
  view.findViewById(R.id.constraintLayout).addFocusables(radioButtonArrayList, View.FOCUS_BACKWARD);
//Log.d("MainActivity:", String.valueOf(findViewById(R.id.toggleButton).isActivated()));
//Log.d("MainActivity:", String.valueOf(findViewById(R.id.toggleButton).isEnabled()));
/*import androidx.compose.material.Icon;
import androidx.compose.material.icons.Icons;
import androidx.compose.material.icons.rounded.Menu;*/
//import androidx.compose.runtime.Composable;
/* Drawable drawable=getDrawable(R.id.ic_menu_mylocation) ;
*/
//((Chip)findViewById(com.example.myrecyclerview_3.R.id.chip7)).setText(getIntent().getStringExtra("name").subSequence(0,4));
//CharSequence charSequence=(CharSequence)getIntent().getStringExtra("name");
//android:text="&lt;"
 /*editText.onHoverEvent()
 editText.onTouchEvent()*/
 /*val myDataset: Array<Array<String?>> = Array(
        0,
    ) { arrayOfNulls<String>(3) }*/
/*
val strImages=myDataset[position][0]
val uri=Uri.parse(strImages)*/
    //override fun getItemCount() = myDataset.size
    /*val myDataset = Array(
            cursor.count
    ) { arrayOfNulls<String>(3) }*/
/*
Log.d("MediaStore_Images_query_1_Activity_recyclerView.hasFocus():",
      recyclerView.hasFocus().toString()*/
    //getApplicationContext().getDeviceId()